package com.fxnotes.book.node;

import com.fxnotes.book.presenter.BooksPresenter;
import com.fxnotes.common.FxUtils;
import com.fxnotes.common.ui.CustomNode;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.fxnotes.domain.model.Book;
import java.util.List;
import javafx.scene.Parent;

@Singleton
public class BooksNode implements CustomNode<Parent> {

    private BooksPresenter presenter;
    private EditEntityComponent<Book> booksComponent;

    public BooksNode() {
        initUI();
    }

    @Inject
    public void setPresenter(BooksPresenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public Parent getNode() {
        return booksComponent.getNode();
    }

    private void initUI() {
        EditEntityHandler<Book> editBooksHandler = new EditEntityHandler<Book>() {

            @Override
            public void onAdd(String name) {
                presenter.addBook(name);
            }

            @Override
            public void onUpdate(Book book, String name) {
                presenter.updateBook(book, name);
            }

            @Override
            public void onRemove(Book book) {
                presenter.removeBook(book);
            }

            @Override
            public void onSelectByDoubleClick(Book book) {
                presenter.openBook(book);
            }
        };
        
        booksComponent = EditEntityComponentBuilder
                .<Book>create()
                .setHeader("Books")
                .setEntityName("book")
                .setHandler(editBooksHandler)
                .build();
    }

    public void reloadBooks(List<Book> books) {
        booksComponent.reload(books, true);
    }

    public void reportError(String message) {
        FxUtils.displayError(booksComponent.getNode().getScene().getWindow(), message);
    }
}
